import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import type { User, UserHouses } from '../config/data/data'

export const useUserStore = defineStore('userStore', () => {
  //个人用户信息
  const userInfo = ref<User>({
    userId: 0,
    username: '未登录',
    avatar: 'https://www.lyzhnb.top/rxls-community/user.svg',
  })

  //拥有房屋
  const houseInfo = ref<UserHouses[]>([])

  //当前选中房屋下标
  const houseIndex = ref(0)

  /**
   * 退出登录，重置化个人信息
   */
  const logout = () => {
    userInfo.value.userId = 0
    userInfo.value.avatar = 'https://www.lyzhnb.top/rxls-community/user.svg'
    userInfo.value.username = '未登录'
    houseInfo.value = []
  }

  /**
   * 登录，初始化个人信息、房屋信息
   */
  const initInfo = (user: User, house: UserHouses[]) => {
    userInfo.value.userId = user.userId
    userInfo.value.avatar = user.avatar
    userInfo.value.username = user.username
    houseInfo.value.push(...house)
  }

  //获取当前才选中的房屋信息
  const getHouseInfo = computed(() => {
    if (houseInfo.value.length == 0) {
      return ''
    }
    let { community, village, roomNumber } = houseInfo.value[houseIndex.value]
    return `${community}-${village}-${roomNumber}`
  })

  /**
   * 判断是否登录,没登录跳转登录
   */
  const isLogin = () => {
    if (userInfo.value.userId == 0) {
      uni.navigateTo({ url: '/subpkg/login/login' })
    }
  }

  return {
    userInfo,
    houseInfo,
    isLogin,
    logout,
    initInfo,
    getHouseInfo,
  }
})
